package org.hzz.caffeine.runner;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.hzz.caffeine.db.UserRepository;
import org.hzz.caffeine.entity.User;
import org.hzz.common.utils.FastJsonUtil;

import java.time.Duration;
import java.util.concurrent.TimeUnit;


/**
 * caffenine基础使用
 *
 * @author 胖卡
 * @version 1.0.0
 * @date 2024/7/14
 */
@Slf4j
public class BasicMain {
    public static void main(String[] args) throws InterruptedException {

        Cache<Integer, User> cache = Caffeine.newBuilder()
                .maximumSize(100)
                .expireAfterWrite(Duration.ofSeconds(1)) // 设置成1s过期
                .build();

        User user = cache.getIfPresent(1);
        log.info("user = {}", user);

        // 如果没有这个数据，那么就进行加载
        user = cache.get(1, UserRepository::getById);

        // 没有从UserRepository里面拿
        user = cache.get(1, UserRepository::getById);
        // 等待2s,然他过期，然后我们再次获取
        TimeUnit.SECONDS.sleep(2);

        user = cache.get(1, UserRepository::getById);
        log.debug("-> \n {} ", FastJsonUtil.toJSONStr(user));
    }
}